// 主 JavaScript 文件
document.addEventListener('DOMContentLoaded', () => {
    // 初始化所有功能
    initNavigation();
    initSmoothScroll();
    initHeroImage();
    initCardAnimations();
});

// 导航菜单功能
function initNavigation() {
    const menuToggle = document.querySelector('.mobile-menu-toggle');
    const navLinks = document.querySelector('.nav-links');
    const header = document.querySelector('.site-header');
    let lastScroll = 0;
    let touchStartY = 0;
    let touchStartX = 0;

    // 移动端菜单切换
    if (menuToggle && navLinks) {
        menuToggle.addEventListener('click', () => {
            const isExpanded = menuToggle.getAttribute('aria-expanded') === 'true';
            menuToggle.setAttribute('aria-expanded', !isExpanded);
            navLinks.classList.toggle('active');
            
            // 更新 ARIA 标签
            menuToggle.setAttribute(
                'aria-label',
                isExpanded ? '打开菜单' : '关闭菜单'
            );
        });

        // 触屏滑动支持
        navLinks.addEventListener('touchstart', (e) => {
            touchStartY = e.touches[0].clientY;
            touchStartX = e.touches[0].clientX;
        }, { passive: true });

        navLinks.addEventListener('touchmove', (e) => {
            if (!navLinks.classList.contains('active')) return;

            const touchY = e.touches[0].clientY;
            const touchX = e.touches[0].clientX;
            const deltaY = touchStartY - touchY;
            const deltaX = touchStartX - touchX;

            // 垂直滑动优先
            if (Math.abs(deltaY) > Math.abs(deltaX)) {
                e.preventDefault();
                const translateY = Math.min(0, Math.max(-100, deltaY));
                navLinks.style.transform = `translateY(${translateY}px)`;
            }
        }, { passive: false });

        navLinks.addEventListener('touchend', () => {
            if (!navLinks.classList.contains('active')) return;

            const currentTransform = window.getComputedStyle(navLinks).transform;
            const matrix = new DOMMatrix(currentTransform);
            const translateY = matrix.m42;

            if (translateY < -50) {
                menuToggle.click();
            } else {
                navLinks.style.transform = '';
            }
        });
    }

    // 滚动时隐藏/显示导航栏
    window.addEventListener('scroll', () => {
        const currentScroll = window.pageYOffset;
        
        if (currentScroll <= 0) {
            header.classList.remove('scroll-up');
            return;
        }
        
        if (currentScroll > lastScroll && !header.classList.contains('scroll-down')) {
            header.classList.remove('scroll-up');
            header.classList.add('scroll-down');
        } else if (currentScroll < lastScroll && header.classList.contains('scroll-down')) {
            header.classList.remove('scroll-down');
            header.classList.add('scroll-up');
        }
        lastScroll = currentScroll;
    });
}

// 平滑滚动功能
function initSmoothScroll() {
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            
            if (targetElement) {
                // 使用 requestAnimationFrame 实现平滑滚动
                const startPosition = window.pageYOffset;
                const targetPosition = targetElement.getBoundingClientRect().top + startPosition;
                const distance = targetPosition - startPosition;
                const duration = 1000;
                let start = null;

                function animation(currentTime) {
                    if (start === null) start = currentTime;
                    const timeElapsed = currentTime - start;
                    const progress = Math.min(timeElapsed / duration, 1);
                    
                    // 使用缓动函数
                    const ease = t => t<.5 ? 2*t*t : -1+(4-2*t)*t;
                    
                    window.scrollTo(0, startPosition + distance * ease(progress));
                    
                    if (timeElapsed < duration) {
                        requestAnimationFrame(animation);
                    }
                }

                requestAnimationFrame(animation);
            }
        });
    });
}

// 英雄图动态加载
function initHeroImage() {
    const heroImage = document.querySelector('.hero-image');
    if (!heroImage) return;

    // 创建 Intersection Observer
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                // 当图片进入视口时加载
                const img = new Image();
                img.src = heroImage.dataset.src;
                img.onload = () => {
                    heroImage.src = img.src;
                    heroImage.classList.add('loaded');
                };
                observer.unobserve(heroImage);
            }
        });
    }, {
        rootMargin: '50px 0px',
        threshold: 0.1
    });

    observer.observe(heroImage);
}

// 卡片动画效果
function initCardAnimations() {
    const cards = document.querySelectorAll('.feature-card');
    if (!cards.length) return;

    // 创建 Intersection Observer 用于卡片动画
    const cardObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate');
                cardObserver.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });

    // 观察所有卡片
    cards.forEach(card => {
        cardObserver.observe(card);
        
        // 添加悬停效果
        card.addEventListener('mouseenter', () => {
            card.style.transform = 'translateY(-5px)';
            card.style.boxShadow = '0 8px 12px rgba(0, 0, 0, 0.15)';
        });

        card.addEventListener('mouseleave', () => {
            card.style.transform = 'translateY(0)';
            card.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1)';
        });
    });
}

// 性能优化：使用 requestIdleCallback 处理非关键任务
if ('requestIdleCallback' in window) {
    requestIdleCallback(() => {
        // 在这里处理非关键任务
        const images = document.querySelectorAll('img[data-src]');
        images.forEach(img => {
            if (img.getBoundingClientRect().top < window.innerHeight * 2) {
                img.src = img.dataset.src;
            }
        });
    });
} 